class AddRightsToTeams < ActiveRecord::Migration
  def self.create_right(name, controller, action)
    Right.create :name => name, :controller => controller, :action => action
  end
  
  def self.remove_right(controller, action)
    Right.find(:all, :conditions => "controller = '#{controller}' AND action = '#{action}'").each do |right|
      RoleRight.find(:all, :conditions => "right_id = #{right.id}").each do |role_right|
        role_right.destroy
      end
      right.destroy
    end
  end
  
  def self.up
    rights = {
      :teams => {
        :list => create_right('Listaa', 'teams', 'list'),
        :new => create_right('Uusi', 'teams', 'new'),
        :create => create_right('Tallennna', 'teams', 'create'),
        :edit => create_right('Muokkaa', 'teams', 'edit'),
        :update => create_right('Tallenna muutokset', 'teams', 'update'),
        :show => create_right('Näytä', 'teams', 'show'),
        :delete_selected => create_right('Poista valitut', 'teams', 'destroy_selected'),
      }
    }
    roles = {:power_user => Role.find_by_name('Tehokäyttäjä'),
      :admin => Role.find_by_name('Järjestelmänvalvoja')}
    roles[:power_user].rights << rights[:teams][:list]
    roles[:power_user].rights << rights[:teams][:show]
    roles[:admin].rights << rights[:teams][:edit]
    roles[:admin].rights << rights[:teams][:update]
    roles[:admin].rights << rights[:teams][:new]
    roles[:admin].rights << rights[:teams][:create]
    roles[:admin].rights << rights[:teams][:delete_selected]
  end
  
  def self.down
    remove_right('teams', 'new')
    remove_right('teams', 'create')
    remove_right('teams', 'edit')
    remove_right('teams', 'update')
    remove_right('teams', 'list')
    remove_right('teams', 'show')
    remove_right('teams', 'delete_selected')
  end
end
